package xaj.weavingtest.ast.istype;

import java.util.Hashtable;
import java.util.Set;

import polyglot.util.Position;
import abc.weaving.aspectinfo.Aspect;
import abc.weaving.aspectinfo.DynamicValuePointcut;
import abc.weaving.aspectinfo.LocalPointcutVars;
import abc.weaving.aspectinfo.Pointcut;
import abc.weaving.aspectinfo.Unification;
import abc.weaving.aspectinfo.Var;
import abc.weaving.matching.MatchingContext;
import abc.weaving.matching.ShadowMatch;
import abc.weaving.matching.WeavingEnv;
import abc.weaving.residues.AlwaysMatch;
import abc.weaving.residues.ContextValue;
import abc.weaving.residues.NeverMatch;
import abc.weaving.residues.Residue;
import abc.weaving.residues.WeavingVar;

public class TargetAny_isType extends DynamicValuePointcut {
	public TargetAny_isType(Position pos) {
        super(pos);
    }

	/*
    public final Residue matchesAt(MatchingContext mc) {
        WeavingEnv we = mc.getWeavingEnv();
        ShadowMatch sm = mc.getShadowMatch();
        
        ContextValue cv=sm.getTargetContextValue();
        if(cv==null) return NeverMatch.v();
        return matchesAt(we,cv);
    }
	*/

    public final Residue matchesAt(MatchingContext mc) {
        WeavingEnv we = mc.getWeavingEnv();
        ShadowMatch sm = mc.getShadowMatch();
        
        ContextValue cv=sm.getTargetContextValue();
        
        Var var = (Var) cv.getSootValue();
        WeavingVar wvar = we.getWeavingVar(var);
    	System.out.println("em TARGETANY(1): matching "+wvar.hashCode()+" with "+cv);
    	MapValues.put(wvar, cv);
    	
        if(cv==null) return NeverMatch.v();
        return matchesAt(we,cv);
    }

    /*
    protected Residue matchesAt(WeavingEnv we,ContextValue cv) {
        return AlwaysMatch.v();
    }
    */
    
    protected Residue matchesAt(WeavingEnv we,ContextValue cv) {
    	
    	Var var = (Var) cv.getSootValue();
        WeavingVar wvar = we.getWeavingVar(var);
    	System.out.println("em TARGETANY(2): matching "+wvar.hashCode()+" with "+cv);
    	MapValues.put(wvar, cv);
    	
        return AlwaysMatch.v();
    }

    public String toString() {
        return "target(*)";
    }
    public void registerSetupAdvice
        (Aspect aspct,Hashtable/*<String,AbcType>*/ typeMap) {}
    public void getFreeVars(Set/*<String>*/ result) {}

    	/* (non-Javadoc)
         * @see abc.weaving.aspectinfo.Pointcut#unify(abc.weaving.aspectinfo.Pointcut, java.util.Hashtable, java.util.Hashtable, abc.weaving.aspectinfo.Pointcut)
         */
        public boolean unify(Pointcut otherpc, Unification unification) {

                if (otherpc.getClass() == this.getClass()) {
                        unification.setPointcut(this);
                        return true;
                } else // Do the right thing if otherpc was a local vars pc
                        return LocalPointcutVars.unifyLocals(this,otherpc,unification);

        }
}
